package com.zh.job;

import cn.hutool.core.thread.RejectPolicy;
import cn.hutool.core.thread.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务线程池
 */
@Slf4j
public class TaskManager {

    public static ThreadPoolExecutor fixedThreadPool =
            new ThreadPoolExecutor(3,
                    10,
                    5,
                    TimeUnit.MINUTES, new ArrayBlockingQueue<>(100),
                    new ThreadFactoryBuilder()
                            .setNamePrefix("FixedThreadPool-")
                            .setUncaughtExceptionHandler((t, e) -> log.error("线程 {} 执行任务时发生异常", t.getName(), e))
                            .build(), RejectPolicy.CALLER_RUNS.getValue());

    public static void execute(Runnable runnable) {
        fixedThreadPool.execute(runnable);
    }


    /**
     * 关闭线程池
     */
    public static void shutdown() {
        fixedThreadPool.shutdown();
        try {
            if (!fixedThreadPool.awaitTermination(60, TimeUnit.SECONDS)) {
                fixedThreadPool.shutdownNow();
            }
        } catch (InterruptedException e) {
            fixedThreadPool.shutdownNow();
        }
    }
}
